package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.user.constant.UserConstant;
import com.tvunetworks.center.user.mapper.UserFeatureRecordMapper;
import com.tvunetworks.center.user.model.Feature;
import com.tvunetworks.center.user.model.User;
import com.tvunetworks.center.user.model.UserFeature;
import com.tvunetworks.center.user.model.UserFeatureRecord;
import com.tvunetworks.center.user.model.param.OwnFeatureUserParam;
import com.tvunetworks.center.user.model.vo.OwnFeatureUserRecordVo;
import com.tvunetworks.center.user.model.vo.OwnFeatureUserVo;
import com.tvunetworks.center.user.service.FeatureService;
import com.tvunetworks.center.user.service.UserFeatureRecordService;
import com.tvunetworks.center.user.service.UserFeatureService;
import com.tvunetworks.center.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: tvucc-aggregator
 * @description: UserFeatureRecordServiceImpl
 * @author lebronchen
 * @create: 2019-06-12 13:24
 **/
@Service
@Slf4j
public class UserFeatureRecordServiceImpl extends BaseService<UserFeatureRecord> implements UserFeatureRecordService {

    @Autowired
    private FeatureService featureService;
    @Autowired
    private UserFeatureService userFeatureService;
    @Autowired
    private UserFeatureRecordMapper userFeatureRecordMapper;
    @Autowired
    private UserService userService;


    @Override
    public void addUserFeatureRecord(UserFeature userFeature) {
        String userId = userFeature.getUserId();
        String featureId = userFeature.getFeatureId();
        long now = System.currentTimeMillis();
        Integer enable = userFeature.getEnable();
        if (enable == 1) {
            // 查询是否有旧的feature没有设置endTime，错误数据需要将endTime置为当前时间
            UserFeatureRecord featureRecord = new UserFeatureRecord()
                    .setUserId(userId)
                    .setFeatureId(featureId)
                    .setEndTime(UserConstant.FeatureRecord.NO_END_TIME);
            List<UserFeatureRecord> existNotEndList = super.selectExistList(featureRecord);
            if (existNotEndList != null && existNotEndList.size() > 0) {
                log.error("AddUserFeatureRecord add feature, exist old FeatureRecord not end. userFeature:[{}] existNotEndList:[{}]", userFeature, existNotEndList);
                for (UserFeatureRecord userFeatureRecord : existNotEndList) {
                    userFeatureRecord.setEndTime(now);
                    super.updateSelective(userFeatureRecord);
                }
            }

            // 新增feature
            featureRecord = new UserFeatureRecord()
                    .setUserId(userId)
                    .setFeatureId(featureId)
                    .setStartTime(now)
                    .setEndTime(UserConstant.FeatureRecord.NO_END_TIME);
            super.insert(featureRecord);
        } else {
            // 移除feature,
            UserFeatureRecord featureRecord = new UserFeatureRecord()
                    .setUserId(userId)
                    .setFeatureId(featureId)
                    .setEndTime(UserConstant.FeatureRecord.NO_END_TIME);
            // 查询是否有已经开启没有结束的UserFeature
            List<UserFeatureRecord> existNotEndList = super.selectExistList(featureRecord);
            if (existNotEndList != null && existNotEndList.size() > 0) {
                // 存在则设置endTime
                for (UserFeatureRecord userFeatureRecord : existNotEndList) {
                    userFeatureRecord.setEndTime(now);
                    super.updateSelective(userFeatureRecord);
                }
            } else {
                // 不存在则创建新的Record，startTime设置为0
                log.error("AddUserFeatureRecord remove feature, not exist old FeatureRecord not end. userFeature:[{}]", userFeature);
                featureRecord = new UserFeatureRecord()
                        .setUserId(userId)
                        .setFeatureId(featureId)
                        .setStartTime(UserConstant.FeatureRecord.NO_START_TIME)
                        .setEndTime(now);
                super.insert(featureRecord);
            }
        }
    }

    @Override
    public PageInfo<OwnFeatureUserVo> pageOwnFeatureUser(LoginUser loginUser, OwnFeatureUserParam param, Integer pageNum, Integer pageSize) {
        Feature feature = featureService.getById(param.getFeatureId());
        if (feature == null) {
            return new PageInfo<>();
        }
        String role = loginUser.getRole();
        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, role)) {
            param.setUserId(loginUser.getId());
            param.setSupport(0);
        } else {
            param.setSupport(1);
        }
        // 分页插件开启分页
        PageHelper.startPage(pageNum, pageSize);

        Integer adminAutoOwn = feature.getAdminAutoOwn();
        param.setAdminAutoOwn(adminAutoOwn);
        List<OwnFeatureUserVo> list =this.listOwnFeatureUser(param);
        // 查询userParentEmail
        for (OwnFeatureUserVo ownFeatureUserVo : list) {
            if (StringUtils.isNotBlank(ownFeatureUserVo.getUserParentId())) {
                User parent = userService.getById(ownFeatureUserVo.getUserParentId());
                ownFeatureUserVo.setUserParentEmail(parent.getEmail());
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public List<OwnFeatureUserVo> listOwnFeatureUser(LoginUser loginUser, OwnFeatureUserParam param) {
        Feature feature = featureService.getById(param.getFeatureId());
        if (feature == null) {
            return new ArrayList<>();
        }
        String role = loginUser.getRole();
        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, role)) {
            param.setUserId(loginUser.getId());
            param.setSupport(0);
        } else {
            param.setSupport(1);
        }
        Integer adminAutoOwn = feature.getAdminAutoOwn();
        param.setAdminAutoOwn(adminAutoOwn);
        List<OwnFeatureUserVo> list =userFeatureRecordMapper.listOwnFeatureUser(param);
        // 查询userParentEmail
        for (OwnFeatureUserVo ownFeatureUserVo : list) {
            if (StringUtils.isNotBlank(ownFeatureUserVo.getUserParentId())) {
                User parent = userService.getById(ownFeatureUserVo.getUserParentId());
                if (parent != null && StringUtils.isNotBlank(parent.getEmail())) {
                    ownFeatureUserVo.setUserParentEmail(parent.getEmail());
                }
            }
        }
        return list;
    }

    private List<OwnFeatureUserVo> listOwnFeatureUser(OwnFeatureUserParam param){
        if (param.getAdminAutoOwn() == 1) {
            return userFeatureRecordMapper.listAutoOwnFeatureUser(param);
        } else {
            return userFeatureRecordMapper.listNotAutoOwnFeatureUser(param);
        }
    }

    @Override
    public List<OwnFeatureUserRecordVo> getOwnFeatureUserRecord(OwnFeatureUserParam param) {
        Feature feature = featureService.getById(param.getFeatureId());
        if (feature == null) {
            return new ArrayList<>();
        }
        User user = userService.getById(param.getUserId());
        if (user == null) {
            return new ArrayList<>();
        }
        // 如果查询的是admin的 admin默认拥有权限，直接返回永远拥有
        if (feature.getAdminAutoOwn() == 1 && StringUtils.equals(LocalConstant.UserRole.ADMIN, user.getRole())) {
            List<OwnFeatureUserRecordVo> list = new ArrayList<>();
            list.add(new OwnFeatureUserRecordVo(UserConstant.FeatureRecord.NO_START_TIME, UserConstant.FeatureRecord.NO_END_TIME));
            return list;
        }
        List<OwnFeatureUserRecordVo> list = userFeatureRecordMapper.getOwnFeatureUserRecord(param);
        if (!CollectionUtils.isEmpty(list)) {
            return list;
        }
        // 如果查不到 Record，但是feature enable,说明feature很早之前就有，并且没有动过，返回之前拥有
        boolean enable = userFeatureService.isUserExistFeature(param.getUserId(), param.getFeatureId());
        if (enable) {
            list.add(new OwnFeatureUserRecordVo(UserConstant.FeatureRecord.NO_START_TIME, UserConstant.FeatureRecord.NO_END_TIME));
            return list;
        }
        return new ArrayList<>();
    }
}
